package com.sens.utils;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;

import com.sens.common.ApplicationUtil;
import com.sens.common.Base64;
import com.sens.common.StringUtil;
import com.sens.commonui.PermissionUtil;
import com.sens.database.LiteOrmDBUtil;
import com.sens.exception.PermissionException;
import com.sens.ipc.mybank.IPCHelper;
import com.sens.ipc.mybank.hooker.Handle;
import com.sens.mybank.utils.MybankUtils;
import com.sens.mybank.utils.SupportVersion;
import com.sens.network.ResponseCallback;
import com.sens.network.ApiByHttp;
import com.sens.orderback.OrderBackApplication;
import com.sens.orderback.ui.activity.mybank.SettingActivity;
import com.sens.tables.MybankConfig;
import com.sens.vo.MybankOrderVo;
import com.yanzhenjie.nohttp.rest.Response;

public class MybankTestHelper {
    private static final int TEST_PROGRESS_GROUP = 201;
    private static final int TEST_PROGRESS_INSTALL = 202;
    private static final int TEST_PROGRESS_RUNNING = 204;
    private static final int TEST_PROGRESS_USERINFO = 205;
    private static final int TEST_PROGRESS_HOST = 206;
    private static final int TEST_PROGRESS_QUERY = 207;
    private static final int TEST_PROGRESS_CONNECT = 208;

    private Activity activity;
    private NoticeLogListener listener;
    private MybankLogFilter logFilter;
    private Handle handle;

    private String userId;

    private boolean selfStartMybank;
    private boolean hasConnect;
    private boolean hasCollectionedOrder;
    private boolean isQueryUserInfo;
    private boolean hasUserInfo;
    private boolean isQueryOrder;

    public MybankTestHelper(Activity a, NoticeLogListener l) {
        this.activity = a;
        this.listener = l;
        this.logFilter = new MybankLogFilter() {
            @Override
            public void updateUserId(String userId) {
                MybankTestHelper.this.userId = userId;
                if (StringUtil.isEmpty(userId)) {
                    logFilter.noticeMessage(StringUtil.createColorText(Color.RED, "未检测到网商银行用户ID，请主动登录网商银行"));
                } else {
                    super.updateUserId(userId);
                    testWithProgress(TEST_PROGRESS_USERINFO);
                }
            }

            @Override
            public void addOrder(MybankOrderVo myBankOrderVo) {
                super.addOrder(myBankOrderVo);
                if (isQueryUserInfo) {
                    ApplicationUtil.moveToTop(activity);
                    isQueryUserInfo = false;
                    hasUserInfo = true;
                    logFilter.noticeMessage(StringUtil.createColorText(Color.BLUE, "账户信息:" + myBankOrderVo.getOwnerName() + myBankOrderVo.getOwnerCardNo()));
                    testWithProgress(TEST_PROGRESS_USERINFO);
                }
                if (!isQueryOrder) return;
                ApplicationUtil.moveToTop(activity);
                isQueryOrder = false;
                hasCollectionedOrder = true;
                logFilter.noticeMessage(StringUtil.createColorText(Color.BLUE, "查询数据成功"));
                testWithProgress(TEST_PROGRESS_QUERY);
            }

            @Override
            public void noticeLog(CharSequence message) {
                super.noticeLog(message);
                if (listener != null) listener.noticeLog(message);
            }
        };
        this.handle = IPCHelper.getHookerHandle(activity, logFilter);
    }

    public interface NoticeLogListener {
        void noticeLog(CharSequence message);
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case TEST_PROGRESS_GROUP:
                case TEST_PROGRESS_HOST:
                    testWithProgress(requestCode);
                    break;
            }
        }
    }

    public void clearLog() {
        logFilter.clearLog();
    }

    public void saveLog() {
        logFilter.saveLog();
    }

    public void unBind() {
        handle.unBind();
        activity = null;
        logFilter = null;
        handle = null;
        listener = null;
        userId = null;
    }

    public Handle getHandle() {
        return handle;
    }

    public void startTest() {
        logFilter.noticeMessage("-----------------------测试-----------------------");
        userId = null;
        hasCollectionedOrder = false;
        hasConnect = false;
        OrderBackApplication.getInstance().setMybankCollectionAble(false);
        testWithProgress(TEST_PROGRESS_GROUP);
    }

    private void testWithProgress(int progress) {
        boolean collectionAble = test(progress);
        if (collectionAble != OrderBackApplication.getInstance().isMybankCollectionAble())
            OrderBackApplication.getInstance().setMybankCollectionAble(collectionAble);
        if (collectionAble) ToastUtil.showToast("检测通过，可在设置中开启模块");
    }

    private boolean test(int progress) {
        if (!testStep1(progress)) return false;
        if (!testStep2(progress)) return false;
        if (!testStep3(progress)) return false;
        if (!testStep4(progress)) return false;
        if (!testStep5(progress)) return false;
        if (!testStep6(progress)) return false;
        if (!testStep7(progress)) return false;
        if (!testStep8(progress)) return false;
        logFilter.noticeMessage(StringUtil.createBiggerColorText(Color.BLUE, "可以正常使用了！"));
        return true;
    }

    private boolean testStep1(int progress) {
        MybankConfig aliPayConfig = LiteOrmDBUtil.getGlobalDBUtil(activity).queryOne(MybankConfig.class);
        if (aliPayConfig == null || StringUtil.isEmpty(aliPayConfig.getChannelNumber())) {
            logFilter.noticeMessage("第一步：检查银行组");
            logFilter.noticeMessage(StringUtil.createColorText(Color.RED, "还未设置银行组"));
            ToastUtil.showToast("请设置银行组");
            activity.startActivityForResult(new Intent(activity, SettingActivity.class), TEST_PROGRESS_GROUP);
            return false;
        } else if (progress <= TEST_PROGRESS_GROUP) {
            logFilter.noticeMessage("第一步：检查银行组");
            handle.setChannelNumber(aliPayConfig.getChannelNumber());
            logFilter.noticeMessage(StringUtil.createColorText(Color.BLUE, "银行组:" + aliPayConfig.getChannelNumber()));
        }
        return true;
    }

    private boolean testStep2(int progress) {
        if (!MybankUtils.checkInstalled(activity)) {
            logFilter.noticeMessage("第二步：检查网商银行是否安装");
            logFilter.noticeMessage(StringUtil.createColorText(Color.RED, "网商银行未安装"));
            return false;
        } else if (progress <= TEST_PROGRESS_GROUP) {
            logFilter.noticeMessage("第二步：检查网商银行是否安装");
            logFilter.noticeMessage(StringUtil.createColorText(Color.BLUE, "网商银行已安装"));
        }
        return true;
    }

    private boolean testStep3(int progress) {
        if (progress <= TEST_PROGRESS_INSTALL) {
            logFilter.noticeMessage("第三步：检查网商银行版本");
            String versionName = ApplicationUtil.getVersionName(activity, new String(Base64.decode("Y29tLm15YmFuay5hbmRyb2lkLnBob25l")));
            boolean supportVersion = false;
            for (String version : SupportVersion.VERSIONS) {
                if (version.equals(versionName)) {
                    supportVersion = true;
                    break;
                }
            }
            if (supportVersion)
                logFilter.noticeMessage(StringUtil.createColorText(Color.BLUE, "网商银行版本:" + versionName));
            else {
                logFilter.noticeMessage(StringUtil.createColorText(Color.RED, "网商银行版本:" + versionName));
                logFilter.noticeMessage(StringUtil.createColorText(Color.RED, "暂不支持当前网商银行版本,支持列表:" + SupportVersion.getSupportVersion()));
                return false;
            }
        }
        return true;
    }

    private boolean testStep4(int progress) {
        try {
            if (!MybankUtils.isRunning(activity)) {
                logFilter.noticeMessage("第四步：检查网商银行是否运行");
                logFilter.noticeMessage(StringUtil.createColorText(Color.RED, "网商银行未运行"));
                ToastUtil.showToast("开始启动网商银行");
                selfStartMybank = true;
                MybankUtils.startMybank(activity);
                activity.getWindow().getDecorView().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (selfStartMybank) {
                            selfStartMybank = false;
                            try {
                                if (MybankUtils.isRunning(activity)) {
                                    ApplicationUtil.moveToTop(activity);
                                    testWithProgress(TEST_PROGRESS_RUNNING);
                                }
                            } catch (PermissionException e) {
                                if (e.getPermissionType() == PermissionException.PERMISSION_TYPE_OPERATION)
                                    requestOperationPermissions(e);
                            }
                        }
                    }
                }, 5000);
                return false;
            } else if (progress <= TEST_PROGRESS_RUNNING) {
                logFilter.noticeMessage("第四步：检查网商银行是否运行");
                logFilter.noticeMessage(StringUtil.createColorText(Color.BLUE, "网商银行已运行"));
            }
        } catch (PermissionException e) {
            if (e.getPermissionType() == PermissionException.PERMISSION_TYPE_OPERATION)
                requestOperationPermissions(e);
            logFilter.noticeMessage("第四步：检查网商银行是否运行");
            logFilter.noticeMessage("请授予重要权限");
            return false;
        }
        return true;
    }

    private void requestOperationPermissions(PermissionException e) {
        PermissionUtil.requestOperationPermissions(activity, new PermissionUtil.OnPermissionCallback() {
            @Override
            protected void onGranted() {
                testWithProgress(TEST_PROGRESS_RUNNING);
            }
        }, e.getMessage());
    }


    private boolean testStep5(int progress) {
//        if (StringUtil.isEmpty(this.userId)) {
        if (!hasUserInfo) {
            logFilter.noticeMessage("第五步：获取网商银行账户信息");
//            handle.checkUserId();
            isQueryUserInfo = true;
            handle.queryOrder();
            return false;
        }
        return true;
    }

    private boolean testStep6(int progress) {
        if (StringUtil.isEmpty(ApiByHttp.getInstance().getHost())) {
            logFilter.noticeMessage("第六步：检查服务器地址");
            logFilter.noticeMessage(StringUtil.createColorText(Color.RED, "服务器地址未设置"));
            ToastUtil.showToast("请设置服务地址");
            activity.startActivityForResult(new Intent(activity, SettingActivity.class), TEST_PROGRESS_HOST);
            return false;
        } else if (progress <= TEST_PROGRESS_HOST) {
            logFilter.noticeMessage("第六步：检查服务器地址");
            logFilter.noticeMessage(StringUtil.createColorText(Color.BLUE, "服务器地址已设置"));
        }
        return true;
    }

    private boolean testStep7(int progress) {
        if (!hasCollectionedOrder) {
            logFilter.noticeMessage("第七步：查询数据");
            isQueryOrder = true;
            handle.queryOrder();
            return false;
        }
        return true;
    }

    private boolean testStep8(int progress) {
        if (!hasConnect) {
            logFilter.noticeMessage("第八步：检查服务器连接状态");
            ApiByHttp.getInstance().uploadMybankOrder(null, new ResponseCallback<String>() {
                @Override
                public void onSucceed(int what, Response<String> response) {
                    super.onSucceed(what, response);
                    if ("数据为空".equals(response.get())) {
                        logFilter.noticeMessage(StringUtil.createColorText(Color.BLUE, "服务器已连接"));
                        hasConnect = true;
                        testWithProgress(TEST_PROGRESS_CONNECT);
                    } else {
                        logFilter.noticeMessage(StringUtil.createColorText(Color.RED, "服务器连接失败"));
                    }
                }

                @Override
                public void onFailed(int what, Response<String> response) {
                    super.onFailed(what, response);
                    logFilter.noticeMessage(StringUtil.createColorText(Color.RED, "服务器连接失败"));
                }
            });
            return false;
        }
        return true;
    }
}
